package com.skytech.component.monitor.enterprise_data_monitoring;

import com.alibaba.fastjson.JSONObject;
import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.task.PartTask;
import com.skytech.component.monitor.util.ChromeBrowser;
import com.skytech.component.monitor.util.ElementAbstractUrl;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class JiangSuService implements CrawlerScript {


    @Autowired
    private SaveDataUtil saveDataUtil;

    @Autowired
    private ChromeBrowser chromeBrowser;


    @Autowired
    private PartTask partTask;


    private static final String province = "江苏省";
    private static final Logger log = LoggerFactory.getLogger(JiangSuService.class);


    public void start() {


        ChromeDriver driver = chromeBrowser.getChromeDriver();
        List<JSONObject> jsonObjects = new ArrayList<>();
        try {
            driver.get("http://218.94.78.61:8080/newPub/web/home.htm");//打开网页
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

            //Thread.sleep(3000);
            try {
                Alert alert = driver.switchTo().alert();
                alert.accept();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            int j = 1;
            partClickNext(driver, null, jsonObjects, j);
            driver.quit();

            partTask.init(jsonObjects);
            partTask.setThreadNum(10);
            partTask.rush();
            /*  enterpriseData(chromeBrowser.getChromeDriver(),jsonObjects);*/

        } catch (Exception e) {
            log.error("{}--网页打开失败--{}", driver.getCurrentUrl(), e.getMessage());
        }


    }


    public void partClickNext(ChromeDriver driver, String html, List<JSONObject> jsonObjects, int j) {


        new WebDriverWait(driver, 5).until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".mini-grid-cell-inner.mini-grid-cell-nowrap")));

        String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");

        Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
        if (html != null) {
            if (html.equals(htmlNew)) {
                log.error("两次链接内容相同,当前页{}", driver.getCurrentUrl());
                return;
            }
        }
        html = htmlNew;
        Elements allElements = parse.getAllElements();
        Elements elementsCity = allElements.select("#dDataGridCardList > div.mini-panel-border.mini-grid-border > div.mini-panel-viewport.mini-grid-viewport > div.mini-panel-body.mini-grid-rows > div.mini-grid-rows-lock > div > table > tbody tr:nth-child(n+2)");
        Elements elementsIndustry = allElements.select("#dDataGridCardList > div.mini-panel-border.mini-grid-border > div.mini-panel-viewport.mini-grid-viewport > div.mini-panel-body.mini-grid-rows > div.mini-grid-rows-view > div > table > tbody tr:nth-child(n+3)");
        JSONObject jsonObject = null;
        if (!elementsCity.isEmpty()) {
            for (int i = 0; i < elementsCity.size(); i++) {
                jsonObject = new JSONObject();
                String url = ElementAbstractUrl.links(elementsCity.get(i).getElementsByTag("td").select(".mini-grid-rightCell").get(0).getElementsByTag("a")).get(0);
                String area = elementsCity.get(i).getElementsByTag("td").get(1).text();
                String industry = elementsIndustry.get(i).getElementsByTag("td").get(0).text();
                jsonObject.put("url", url);
                jsonObject.put("area", area);
                jsonObject.put("industry", industry);
                jsonObjects.add(jsonObject);
                //urlList.add(url);
            }

        }
        //partTask(jsonObjects);


        try {
            log.info("当前页--{}", driver.getCurrentUrl());

            WebElement webElement = driver.findElementByXPath("//*[@id='mini-60']/span");
            log.error("当前页数--{}", j);
            try {
                Alert alert = driver.switchTo().alert();
                alert.accept();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            webElement.click();
            j++;

            Thread.sleep(3000);

        } catch (Exception e) {
            log.error("点击下一页出错--{}", e.getMessage());
        }

        partClickNext(driver, html, jsonObjects, j);

    }


    public void enterpriseData(ChromeDriver driver, List<JSONObject> jsonObjects) {
        // List<JSONObject> urlSonList = new ArrayList<>();
        for (JSONObject json : jsonObjects) {
            JSONObject jsonObject = new JSONObject();
            try {
                try {
                    driver.get(json.get("url").toString());
                    Thread.sleep(3000);
                } catch (Exception e) {
                    log.error("网页打开失败--{}", driver.getCurrentUrl());
                }

                driver.switchTo().frame(driver.findElementByXPath("//*[@id=\"mini-3$body$1\"]/iframe"));
                //String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
                String address = driver.findElementByCssSelector("#enterpriseForm > table > tbody > tr:nth-child(6) > td.tf_l > span > span > input").getAttribute("value");
                // Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
                // Elements allElements = parse.getAllElements();
                // String address=allElements.select(".BMap_bubble_content").text().split("：")[1];
       /*         if (address.isEmpty()) {
                    Thread.sleep(3000);
                    address = driver.findElementByCssSelector("#enterpriseForm > table > tbody > tr:nth-child(6) > td.tf_l > span > span > input").getAttribute("value");
                }*/
                jsonObject.put("address", address);

                log.info("当前页面--{}", driver.getCurrentUrl());
                try {
                    Alert alert = driver.switchTo().alert();
                    alert.accept();
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                driver.switchTo().defaultContent();

                driver.findElementByXPath("//*[@id='mini-3$3']/span").click();

                Thread.sleep(3000);
            } catch (Exception e) {
                log.error("元素点击出错--{},当前页面为{}", e.getMessage(), driver.getCurrentUrl());
                continue;
            }
            String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
            Document parseNew = Jsoup.parse(htmlNew, driver.getCurrentUrl());
            Elements allElementsNew = parseNew.getAllElements();
            String entName = allElementsNew.select("#enterpriseName").get(0).text();
            String urlSon = driver.findElementByXPath("//*[@id='mini-3$body$3']/iframe").getAttribute("src");
            try {
                driver.switchTo().defaultContent();
                driver.findElementByXPath("//*[@id=\"mini-3$4\"]/span").click();
                Thread.sleep(3000);
            } catch (Exception e) {
                log.error("元素点击出错--{},当前页面为{}", e.getMessage(), driver.getCurrentUrl());
                continue;
            }
            String urlHand = driver.findElementByXPath("//*[@id=\"mini-3$body$4\"]/iframe").getAttribute("src");

            jsonObject.put("href", urlSon);
            jsonObject.put("entName", entName);
            jsonObject.put("area", json.get("area").toString());
            jsonObject.put("industry", json.get("industry").toString());
            jsonObject.put("urlHand", urlHand);

            // urlSonList.add(jsonObject);

            getDetailEnterpriseData(driver, jsonObject);
            getDetailEnterpriseDataHand(driver, jsonObject);
        }
        driver.quit();
    }

    public void getDetailEnterpriseDataHand(ChromeDriver driver, JSONObject jsonObject) {
        boolean mark = true;
        try {
            driver.get(jsonObject.getString("urlHand"));
            Thread.sleep(3000);

            String htmlBody = driver.findElementByTagName("html").getAttribute("outerHTML");
            Document parseBody = Jsoup.parse(htmlBody, driver.getCurrentUrl());
            Elements allElementsBody = parseBody.getAllElements();
            List<String> stringList = allElementsBody.select("#monitorAutoDataGrid > div.mini-panel-border.mini-grid-border > div.mini-panel-viewport.mini-grid-viewport > div.mini-panel-body.mini-grid-rows > div.mini-grid-rows-view > div > table > tbody tr:nth-child(n+3) td:nth-child(5)").eachText();
            List<WebElement> webElementList = driver.findElementsByCssSelector("#monitorAutoDataGrid > div.mini-panel-border.mini-grid-border > div.mini-panel-viewport.mini-grid-viewport > div.mini-panel-body.mini-grid-rows > div.mini-grid-rows-view > div > table > tbody tr:nth-child(n+3) td:nth-child(3)");
            if (webElementList.isEmpty()) {
                Thread.sleep(2000);
                webElementList = driver.findElementsByCssSelector("#monitorAutoDataGrid > div.mini-panel-border.mini-grid-border > div.mini-panel-viewport.mini-grid-viewport > div.mini-panel-body.mini-grid-rows > div.mini-grid-rows-view > div > table > tbody tr:nth-child(n+3) td:nth-child(3)");
            }
            if (!webElementList.isEmpty()) {
                for (int i = 0; i < webElementList.size(); i++) {
                    jsonObject.put("rate", stringList.get(i));
                    List<MonitorData> monitorDataList = new ArrayList<>();
                    try {
                        Alert alert = driver.switchTo().alert();
                        alert.accept();
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                    webElementList.get(i).click();

                    Thread.sleep(1000);
                    if (stringList.get(i).equals("连续/日/次")) {

                        driver.findElementByCssSelector("#dStart > span > span > span.mini-buttonedit-button > span").click();
                        String timestap = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " " + "00:00:00";

                        SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

                        Date parse = sd1.parse(timestap);
                        String Xpath = "//*[@id=\"mini-21$" + parse.getTime() + "\"]";
                        driver.findElementByXPath(Xpath).click();
                        driver.findElementByCssSelector("#dEnd > span > span > span.mini-buttonedit-button > span").click();
                        driver.findElementByCssSelector("#mini-21 > tbody > tr:nth-child(2) > td > div > span:nth-child(2)").click();
                        driver.findElementByCssSelector("#btnSearch > span").click();
                        Thread.sleep(2000);
                    }

                    jsonObject.put("monitor_type", "手工监测");

                    clickNextPage(driver, null, jsonObject, monitorDataList);

                    if (!monitorDataList.isEmpty()) {
                        saveDataUtil.saveTag(monitorDataList, province);
                        mark = true;
                    } else {
                        mark = false;
                    }
                }
                if (!mark) {
                    log.error("当前企业手工监测点位无数据--{}", jsonObject.getString("entName"));
                }
            } else {
                log.error("当前企业无手工监测点位--{}", jsonObject.getString("entName"));
            }
        } catch (Exception e) {
            log.error("网页打开失败--{},当前企业--{}", e.getMessage(), jsonObject.getString("entName"));
            return;
        }

    }


    public void getDetailEnterpriseData(ChromeDriver driver, JSONObject jsonObject) {
        boolean mark = true;
        try {
            driver.get(jsonObject.get("href").toString());
            Thread.sleep(3000);

            String htmlBody = driver.findElementByTagName("html").getAttribute("outerHTML");
            Document parseBody = Jsoup.parse(htmlBody, driver.getCurrentUrl());
            Elements allElementsBody = parseBody.getAllElements();
            List<String> stringList = allElementsBody.select("#monitorAutoDataGrid > div.mini-panel-border.mini-grid-border > div.mini-panel-viewport.mini-grid-viewport > div.mini-panel-body.mini-grid-rows > div.mini-grid-rows-view > div > table > tbody tr:nth-child(n+3) td:nth-child(5)").eachText();
            List<WebElement> webElementList = driver.findElementsByCssSelector("#monitorAutoDataGrid > div.mini-panel-border.mini-grid-border > div.mini-panel-viewport.mini-grid-viewport > div.mini-panel-body.mini-grid-rows > div.mini-grid-rows-view > div > table > tbody tr:nth-child(n+3) td:nth-child(3)");
            if (webElementList.isEmpty()) {
                Thread.sleep(2000);
                webElementList = driver.findElementsByCssSelector("#monitorAutoDataGrid > div.mini-panel-border.mini-grid-border > div.mini-panel-viewport.mini-grid-viewport > div.mini-panel-body.mini-grid-rows > div.mini-grid-rows-view > div > table > tbody tr:nth-child(n+3) td:nth-child(3)");
            }
            if (!webElementList.isEmpty()) {
                for (int i = 0; i < webElementList.size(); i++) {
                    jsonObject.put("rate", stringList.get(i));
                    List<MonitorData> monitorDataList = new ArrayList<>();
                    try {
                        Alert alert = driver.switchTo().alert();
                        alert.accept();
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                    webElementList.get(i).click();

                    Thread.sleep(1000);
                    if (stringList.get(i).equals("连续/日/次")) {
                        driver.findElementByCssSelector("#dStart > span > span > span.mini-buttonedit-button > span").click();
                        String timestap = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " " + "00:00:00";

                        SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

                        Date parse = sd1.parse(timestap);
                        String Xpath = "//*[@id=\"mini-21$" + parse.getTime() + "\"]";
                        driver.findElementByXPath(Xpath).click();
                        driver.findElementByCssSelector("#dEnd > span > span > span.mini-buttonedit-button > span").click();
                        driver.findElementByCssSelector("#mini-21 > tbody > tr:nth-child(2) > td > div > span:nth-child(2)").click();
                        driver.findElementByCssSelector("#btnSearch > span").click();
                        Thread.sleep(2000);
                    }
                    jsonObject.put("monitor_type", "自动监测");
                    clickNextPage(driver, null, jsonObject, monitorDataList);

                    if (!monitorDataList.isEmpty()) {
                        saveDataUtil.saveTag(monitorDataList, province);
                        mark = true;
                    } else {
                        mark = false;
                    }
                }
                if (!mark) {
                    log.error("当前企业自动监测点位无数据--{}", jsonObject.getString("entName"));
                }
            } else {
                log.error("当前企业无自动监测点位--{}", jsonObject.getString("entName"));
            }
        } catch (Exception e) {
            log.error("网页打开失败--{},当前企业--{}", e.getMessage(), jsonObject.getString("entName"));
            return;
        }
    }

    private void clickNextPage(ChromeDriver driver, String html, JSONObject jsonObject, List<MonitorData> monitorDataList) {
        String htmlBody = driver.findElementByTagName("html").getAttribute("outerHTML");
        Document parseBody = Jsoup.parse(htmlBody, driver.getCurrentUrl());
        if (html != null) {
            if (html.equals(htmlBody)) {
                log.error("两次链接内容相同,当前页{}", driver.getCurrentUrl());
                return;
            }
        }
        html = htmlBody;
        Elements allElementsBody = parseBody.getAllElements();
        Elements elementBody = allElementsBody.select("#GridFormGrid > div.mini-panel-border.mini-grid-border > div.mini-panel-viewport.mini-grid-viewport > div.mini-panel-body.mini-grid-rows > div.mini-grid-rows-view > div > table > tbody tr:nth-child(n+3)");
        // #GridFormGrid > div.mini-panel-border.mini-grid-border > div.mini-panel-viewport.mini-grid-viewport > div.mini-panel-body.mini-grid-rows > div.mini-grid-rows-view > div > table > tbody

        if (!elementBody.isEmpty()) {
            for (Element e : elementBody) {
                //MonitorData monitorData=monitorDataDAO.findByCompanyNameAndMonitorInfoAndMonitorPoint();

                MonitorData monitorData = new MonitorData();
                monitorData.setId(UUID.randomUUID().toString());
                monitorData.setProvince(province);
                monitorData.setCompanyName(jsonObject.get("entName").toString());
                monitorData.setMonitorRate(jsonObject.getString("rate"));
                monitorData.setArea(jsonObject.getString("area"));
                monitorData.setIndustry(jsonObject.getString("industry"));
                monitorData.setAddress(jsonObject.getString("address"));
                monitorData.setMonitorPoint(e.getElementsByTag("td").get(1).text());
                monitorData.setMonitorTime(e.getElementsByTag("td").get(2).text());
                monitorData.setMonitorInfo(e.getElementsByTag("td").get(3).text());
                monitorData.setMonitorValue(e.getElementsByTag("td").get(4).text());
                monitorData.setMonitorType(jsonObject.getString("monitor_type"));
                monitorData.setMonitorStandardValue(e.getElementsByTag("td").get(5).text() + "--" + e.getElementsByTag("td").get(6).text());
                monitorData.setOverproof(e.getElementsByTag("td").get(7).text());
                monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                monitorDataList.add(monitorData);

            }


            try {

                WebElement webElement = driver.findElementByXPath("//*[@id='mini-37']/span");
                try {
                    Alert alert = driver.switchTo().alert();
                    alert.accept();
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                webElement.click();
                Thread.sleep(3000);
                clickNextPage(driver, html, jsonObject, monitorDataList);
            } catch (Exception e) {
                log.error(e.getMessage());
                return;
            }
        }


    }


}


